var crypto = require('crypto');
var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var moment = require('moment');
var post = require('wordtocms');

/*
	ESTABLISH DATABASE CONNECTION
*/

var dbName = process.env.DB_NAME || 'node-login';
var dbHost = process.env.DB_HOST || 'localhost';
var dbPort = process.env.DB_PORT || 27017;

var db = new MongoDB(dbName, new Server(dbHost, dbPort, { auto_reconnect: true }), { w: 1 });
db.open(function (e, d) {
    if (e) {
        console.log(e);
    } else {
        if (process.env.NODE_ENV == 'live') {
            db.authenticate(process.env.DB_USER, process.env.DB_PASS, function (e, res) {
                if (e) {
                    console.log('mongo :: error: not authenticated', e);
                }
                else {
                    console.log('mongo :: authenticated and connected to database :: "' + dbName + '"');
                }
            });
        } else {
            console.log('mongo :: connected to database :: "' + dbName + '"');
        }
    }
});

var informations = db.collection('informations');
var files = db.collection('files');

exports.proxyInformation = function (body) {
    const data = body.content ? body.content.replace(/.*?base64,/, function (str) {
        return '';
    }) : '';
    const bufferData = new Buffer(data, 'base64');
    const taskItem = body.taskItem; 

    return post({content: bufferData, title: taskItem.name, summary: taskItem.description});
};

exports.addInformation = function (newData, callback) {
    newData.date = moment().format('MMMM Do YYYY, h:mm:ss a');
    saltAndHash(JSON.stringify(newData.taskItem) + newData.date, function (hash) {
        newData.taskItem.index = hash;
        files.save({ index: hash, content: newData.content }, { safe: true }, function () {
            informations.insert({
                user: newData.user,
                taskItem: JSON.stringify(newData.taskItem),
                index: hash,
                date: newData.date
            }, { safe: true }, callback);
        });
    });
}

exports.getInformation = function (a, callback) {
    informations.find(a).toArray(
        function (e, res) {
            if (e) callback(e)
            else callback(null, res)
        }
    );
}

exports.deleteInformation = function (a, callback) {
    files.remove({ index: a.index }, function (e, o) {
        informations.remove(a, callback);
    });
}

exports.publishInformation = function (a, callback) {
    informations.findOne(a, function (e, o) {
        if (o) {
            o.publish = true;
            informations.save(o, callback);
        } else {
            callback(true, null);
        }
    });
}

exports.filterInformation = function (callback) {
    informations.find({ publish: true }).toArray(
        function (e, res) {
            if (e) callback(e);
            else callback(null, res);
        }
    );
}
//admin operate database
exports.delAllRecords = function (callback) {
    informations.remove({}, callback);
}

exports.getAllRecords = function (callback) {
    informations.find({}).toArray(
        function (e, res) {
            if (e) callback(e)
            else callback(null, res)
        }
    );
}


/* private encryption & validation methods */
var generateSalt = function () {
    var set = '0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
    var salt = '';
    for (var i = 0; i < 10; i++) {
        var p = Math.floor(Math.random() * set.length);
        salt += set[p];
    }
    return salt;
}

var md5 = function (str) {
    return crypto.createHash('md5').update(str).digest('hex');
}

var saltAndHash = function (pass, callback) {
    var salt = generateSalt();
    callback(salt + md5(pass + salt));
}
